package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import androidx.annotation.NonNull;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;
import com.qiantu.api.entity.WeatherValueBean;

import java.util.LinkedHashMap;
import java.util.List;

public final class WeatherValueAdapter extends AppAdapter<WeatherValueBean> {

    private LinkedHashMap<Integer, WeatherValueBean> selected = new LinkedHashMap();
    public WeatherValueAdapter(Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private ViewHolder() {
            super(R.layout.item_weather);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if(view instanceof CheckBox){
                CheckBox checkBox = (CheckBox) view;
                WeatherValueBean data = (WeatherValueBean) view.getTag();
                if(checkBox.isChecked()){
                    selected.put(data.getValue(), data);
                }else{
                    selected.remove(data.getValue());
                }
            }
            super.onClick(view);
        }

        @Override
        public void onBindView(int position) {
            WeatherValueBean weather = getItem(position);
            CheckBox checkBox = (CheckBox) itemView;
            if(selected.get(weather.getValue()) != null){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }
            int nameRes = getResources().getIdentifier(weather.getName(), "string", getContext().getPackageName());
            checkBox.setText(nameRes);
            itemView.setTag(weather);
        }
    }

    public LinkedHashMap getSelected() {
        return selected;
    }

    public void checked(List<WeatherValueBean> checked){
        selected.clear();
        if(checked != null && checked.size() > 0){
            for(WeatherValueBean weather : checked){
                selected.put(weather.getValue(), weather);
            }
            notifyDataSetChanged();
        }
    }

//    public void checked(List<Integer> checked){
//        selected.clear();
//        if(checked != null && checked.size() > 0){
//            for(int value : checked){
//                for(WeatherValueBean weatherValueBean : getData()){
//                    if(weatherValueBean.getValue() == value){
//                        selected.put(value, weatherValueBean);
//                        break;
//                    }
//                }
//            }
//        }
//        notifyDataSetChanged();
//    }
}